package com.xiaocg.base.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xiaocg
 */

class ShareResource{
    private int flag =1;
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public  void  print5(int i){
        lock.lock();
        try {
            while (flag!=1){
                c1.await();
            }
            for (int j=0;j<5;j++) {
                System.out.println(Thread.currentThread().getName() + " :: " + (j+1)+" 次" + "第 "+i+"轮");
            }
            flag=2;

            c2.signal();
        }catch (Exception e){

        } finally {
            lock.unlock();
        }
    }
    public  void  print6(int i){
        lock.lock();
        try {
            while (flag!=2){
                c2.await();
            }
            for (int j=0;j<6;j++) {
                System.out.println(Thread.currentThread().getName() + " :: " + (j+1)+" 次" + "第 "+i+"轮");
            }
            flag=3;

            c3.signal();
        }catch (Exception e){

        } finally {
            lock.unlock();
        }
    }
    public  void  print7(int i){
        lock.lock();
        try {
            while (flag!=3){
                c3.await();
            }
            for (int j=0;j<7;j++) {
                System.out.println(Thread.currentThread().getName() + " :: " + (j+1)+" 次" + "第 "+i+"轮");
            }
            flag=1;
            c1.signal();
        }catch (Exception e){

        } finally {
            lock.unlock();
        }
    }
}

public class LockDemo2 {

    public static void main(String[] args) {
        ShareResource s = new ShareResource();

        new Thread(() -> {
            for (int i=0;i<10;i++) {
                s.print5(i);
            }
        }, "aaa").start();
        new Thread(() -> {
            for (int i=0;i<10;i++) {
                s.print6(i);
            }
        }, "bbb").start();
        new Thread(() -> {
            for (int i=0;i<10;i++) {
                s.print7(i);
            }
        }, "ccc").start();

    }
}
